<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}股票实时AI分析系统{% endblock %}</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css">
    <style>
        /* 完整内联style.css */
        body {
            padding-bottom: 70px;
            background-color: #f8f9fa;
        }

        .jumbotron {
            padding: 2rem;
            background-color: #e9ecef;
            border-radius: 0.3rem;
            margin-bottom: 2rem;
        }

        .footer {
            position: fixed;
            bottom: 0;
            width: 100%;
            height: 60px;
            line-height: 60px;
            background-color: #f5f5f5;
            z-index: 100;
        }

        /* Stock list styles */
        .stock-card {
            transition: transform 0.3s;
            margin-bottom: 20px;
        }

        .stock-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .price-up {
            color: #28a745;
        }

        .price-down {
            color: #dc3545;
        }

        /* Status indicators */
        .status-healthy {
            color: #28a745;
        }

        .status-degraded {
            color: #ffc107;
        }

        .status-unhealthy {
            color: #dc3545;
        }

        /* Log viewer styles */
        .log-container {
            max-height: 600px;
            overflow-y: auto;
            background-color: #f8f9fa;
            font-family: monospace;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        /* Chart styles */
        .chart-container {
            height: 400px;
            margin-bottom: 20px;
        }

        /* Log level styles */
        .log-info {
            color: #0d6efd;
        }

        .log-warning {
            color: #ffc107;
        }

        .log-error {
            color: #dc3545;
        }

        .log-critical {
            color: #dc3545;
            font-weight: bold;
        }

        /* Strategy indicators */
        .strategy-buy {
            color: #28a745;
            font-weight: bold;
        }

        .strategy-sell {
            color: #dc3545;
            font-weight: bold;
        }

        .strategy-hold {
            color: #6c757d;
        }
    </style>
    {% block head %}{% endblock %}
</head>

<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="/">股票实时AI分析系统</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link" href="/">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/stocks">股票列表</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/status">系统状态</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/logs">系统日志</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        {% block content %}{% endblock %}
    </div>

    <footer class="footer mt-auto py-3 bg-light">
        <div class="container text-center">
            <span class="text-muted">股票实时AI分析系统 © 2025</span>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.socket.io/4.6.0/socket.io.min.js"></script>
    <script>
        // 内联必要的JS功能
        let socket;

        document.addEventListener('DOMContentLoaded', function () {
            // 初始化Socket.io连接
            if (typeof io !== 'undefined') {
                socket = io();

                socket.on('connect', function () {
                    console.log('WebSocket已连接');
                });

                socket.on('log_update', function (data) {
                    appendLog(data.log, data.level);
                });

                // 在日志页面请求初始日志
                if (window.location.pathname === '/logs') {
                    socket.emit('request_logs');

                    socket.on('initial_logs', function (data) {
                        const logContainer = document.getElementById('log-container');
                        if (logContainer) {
                            logContainer.innerHTML = '';
                            data.logs.forEach(log => {
                                appendLog(log);
                            });
                        }
                    });
                }
            }

            // 初始化图表（如果存在）
            const chartContainer = document.getElementById('stock-chart');
            if (chartContainer && window.chartData) {
                try {
                    initializeStockChart(chartContainer, window.chartData);
                } catch (e) {
                    console.error('初始化图表失败:', e);
                }
            }

            // 绑定分析按钮事件
            const analyzeButtons = document.querySelectorAll('.btn-analyze');
            analyzeButtons.forEach(button => {
                button.addEventListener('click', function () {
                    const stockCode = this.getAttribute('data-stock');
                    const analyzerType = this.getAttribute('data-analyzer') || null;

                    if (stockCode) {
                        startAnalysis(stockCode, analyzerType);
                        this.disabled = true;
                        this.innerHTML = '<span class="spinner-border spinner-border-sm"></span> 分析中...';
                    }
                });
            });
        });

        function appendLog(log, level) {
            const logContainer = document.getElementById('log-container');
            if (!logContainer) return;

            const logLine = document.createElement('div');
            if (level) {
                logLine.className = `log-${level.toLowerCase()}`;
            }
            logLine.textContent = log;
            logContainer.appendChild(logLine);
            logContainer.scrollTop = logContainer.scrollHeight;
        }

        function startAnalysis(stockCode, analyzerType) {
            fetch('/api/analyze', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    stock_code: stockCode,
                    analyzer_type: analyzerType
                })
            })
                .then(response => response.json())
                .then(data => {
                    showNotification(`开始分析股票 ${stockCode}`);
                    if (data.error) {
                        showNotification(`分析请求失败: ${data.error}`);
                        // 重置按钮状态
                        resetAnalyzeButtons(stockCode);
                    }
                })
                .catch(error => {
                    showNotification(`分析请求错误: ${error}`);
                    resetAnalyzeButtons(stockCode);
                });
        }

        function resetAnalyzeButtons(stockCode) {
            const buttons = document.querySelectorAll(`.btn-analyze[data-stock="${stockCode}"]`);
            buttons.forEach(button => {
                button.disabled = false;
                button.innerHTML = '分析';
            });
        }

        function showNotification(message) {
            const container = document.createElement('div');
            container.className = 'position-fixed top-0 end-0 p-3';
            container.style.zIndex = '1050';

            container.innerHTML = `
                <div class="toast show" role="alert" aria-live="assertive" aria-atomic="true">
                    <div class="toast-header">
                        <strong class="me-auto">系统通知</strong>
                        <small>${new Date().toLocaleTimeString()}</small>
                        <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
                    </div>
                    <div class="toast-body">${message}</div>
                </div>
            `;

            document.body.appendChild(container);
            setTimeout(() => {
                container.remove();
            }, 3000);
        }

        function initializeStockChart(container, data) {
            if (!data || !data.dates || data.dates.length === 0) {
                container.innerHTML = '<div class="alert alert-warning">无图表数据</div>';
                return;
            }

            const ctx = container.getContext('2d');

            // 解构数据
            const { dates, opens, highs, lows, closes, volumes } = data;

            // 创建蜡烛图数据
            const candleData = dates.map((date, i) => ({
                x: date,
                o: opens[i],
                h: highs[i],
                l: lows[i],
                c: closes[i]
            }));

            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: dates,
                    datasets: [{
                        label: '收盘价',
                        data: closes,
                        borderColor: '#0d6efd',
                        backgroundColor: 'rgba(13, 110, 253, 0.1)',
                        fill: true,
                        tension: 0.1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        x: {
                            title: {
                                display: true,
                                text: '日期'
                            }
                        },
                        y: {
                            title: {
                                display: true,
                                text: '价格'
                            }
                        }
                    }
                }
            });
        }
    </script>
    {% block scripts %}{% endblock %}
</body>

</html>